<template>
  <!--    图册管理-->
  <div class="page">
    <div class="manage">
      <el-button size="mini" class="btn" @click="addPic">
        <em class="el-icon-circle-plus-outline" />
        <span>新增</span>
      </el-button>
      <div class="search flex-center-start">
        <div class="icon-search"></div>
        <el-input
          size="mini"
          v-model="keyWords"
          placeholder="请搜索"
          @keyup.enter.native="search"
          ref="inp"
          maxlength="100"
        ></el-input>
      </div>
      <el-button type="primary" size="mini" @click="search">搜索</el-button>
      <el-button type="primary" size="mini" @click="infoClean">清空</el-button>
    </div>
    <div class="listAll">
      <ul class="listTitle">
        <li>序号</li>
        <li>图册名称</li>
        <li>描述</li>
        <li>上传时间</li>
        <li>创建人</li>
        <li>操作</li>
      </ul>
      <div class="list">
        <ul v-for="(item, index) in newList" :key="index">
          <li>{{ index + 1 }}</li>
          <li :title="item.atlasName">{{ item.atlasName }}</li>
          <li :title="item.memo">{{ item.memo }}</li>
          <li>{{ item.createDate.slice(0, 10) }}</li>
          <li>{{item.operator?item.operator:'游客'}}</li>
          <li>
            <div class="btn" @click="editPic(item)">
              <img src="../../assets/common/edit.png" alt="" />
              <span>编辑</span>
            </div>
            <!-- <div @click="picListDetail">
              <img src="../assets/common/view.png" alt="" />
              <span>详情</span>
            </div> -->
            <div
              class="btn"
              style="background: #e64f4f"
              @click="deleteInfo(item.id)"
            >
              <img src="../../assets/common/del.png" alt="" />
              <span>删除</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <synchronization></synchronization>
    <!-- <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      background
      :current-page.sync="current"
      :page-size="9"
      layout="prev, pager, next, jumper"
      :total="this.list.length"
      style="text-align: right; margin: 0.2rem 0.6rem 0.2rem 0"
    >
    </el-pagination> -->
    <!-- 分页 -->
    <div class="image-pagination">
      <el-pagination
        background
        small
        layout="prev, pager, next, total, jumper"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="pageSize"
        :total="total"
        :key="paginationKey"
      >
      </el-pagination>
    </div>
    <!--        编辑-->
    <el-dialog :title="title" width="8rem" :visible.sync="editDialogVisible">
      <el-form
        :label-position="labelPosition"
        label-width="1.5rem"
        :model="formLabelAlign"
        ref="ruleForm2"
        :rules="rules"
      >
        <el-form-item label="图册名称：" prop="name">
          <el-input v-model="formLabelAlign.name" maxlength="200"></el-input>
        </el-form-item>
        <el-form-item label="图册描述：">
          <el-input
            v-model="formLabelAlign.memo"
            maxlength="255"
            :autosize="{ minRows: 2 }"
            type="textarea"
          ></el-input>
        </el-form-item>
        <slot></slot>
        <el-form-item label="上传文件：" required>
          <el-upload
            class="upload-demo"
            :action="baseURL"
            :on-success="handleSuccess"
            :multiple="false"
            :before-upload="beforeUpload"
            :auto-upload="true"
            :data="uploadOtherData"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-error="handError"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div> -->
          </el-upload>
         </el-form-item>
          <div class="footer flex-center">
            <div class="cancel" @click="editDialogVisible = false">取消</div>
            <div class="confirm" @click="editSubmit()">确定</div>
          </div>
      </el-form>
    </el-dialog>
    <!--        新增-->
    <el-dialog :title="title" width="8rem" :visible.sync="addDialogVisible">
      <el-form
        :label-position="labelPosition"
        label-width="1.5rem"
        :model="addLabelAlign"
        ref="ruleForm1"
        :rules="rules"
      >
        <el-form-item label="图册名称：" prop="name">
          <el-input
            placeholder="请输入图册名称"
            v-model="addLabelAlign.name"
            maxlength="200"
          ></el-input>
        </el-form-item>
        <el-form-item label="图册描述：">
          <el-input
            placeholder="请输入描述"
            v-model="addLabelAlign.memo"
            maxlength="255"
            :autosize="{ minRows: 2 }"
            type="textarea"
          ></el-input>
        </el-form-item>
        <slot></slot>
        <el-form-item label="上传文件：" required>
          <el-upload
            class="upload-demo"
            :action="baseURL"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :auto-upload="true"
            :data="uploadOtherData"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div> -->
          </el-upload>
         </el-form-item>
          <div class="footer flex-center">
            <div class="cancel" @click="addDialogVisible = false">取消</div>
            <div class="confirm" @click="addSubmit()">确定</div>
          </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import synchronization from "../common/synchronizationDialog";

import { mapState } from "vuex";
export default {
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      current: 1,
      total: null,
      pageSize: 10,
      paginationKey: 0, // 解决currentPage 不动态绑定的问题
      // 模态框的名字
      title: "新增",
      // 上传文件后文件所在列表
      fileList: [],
      // 默认输入框前面的标题右居中显示
      labelPosition: "right",
      // 输入框的内容  便于双向绑定
      formLabelAlign: {
        //编辑模态框里的内容
        name: "",
        memo: "",
        id: "",
      },
      rules: {
        name: [
            { required: true, message: '请输入图册名称', trigger: 'blur'},
            { min: 1, max: 200, message: '名称范围为1-200字符', trigger: 'blur'}
        ]
      },
      submitLoading: null,
      addLabelAlign: {
        //新增模态框里的内容
        name: "",
        memo: "",
      },
      baseURL: `${window.VUE_APP_BASE_URL}/photoAlbum/uploadPhotoAlbumFile`, //上传的地址
      loading: null, //上传时的加载中
      uploadOtherData: null,
      keyWords: "", //搜索时输入值
      newList: [],
      // allList: [], //未单击目标树显示的全部分页数组
      // arrList: [], //单击目标树下的分页数组
      // listTotal: [], //单击目标树下的全部数组
      // allListTotal: [], //未单击目标树下的全部数组
    };
  },
  props: {
    selectedTabId: {
      default: () => "2",
    },
  },
  computed: {
    ...mapState({
      pictureTreeChecked(state) {
        return state.app.pictureTreeChecked; //监听左侧目标树的被单击的id数组
      },
    }),
    list() {
      if (this.pictureTreeChecked.length === 0) {
        return this.allListTotal;
      } else {
        return this.listTotal;
      }
    },
    // uploadAccept() {
    //   return "application/msword,application/pdf,application/vnd.ms-powerpoint,application/wps-office.ppt,application / wps - office.pdf,application / wps - office.wps,application / wps - office.dps,application / wps - office.docx,application / wps - office.doc,application / octet - stream";
    // },
  },
  watch: {
    pictureTreeChecked() {
      this.getCurrentPhotoAlbum();
    },
    // keyWords() {
    //   this.getCurrentPhotoAlbum(null, null, 1);
    // },
  },
  created() {
    // this.tAtlasTypeInfoFindAll();
    this.getCurrentPhotoAlbum();
    // console.log(this.pictureTreeChecked);
    // this.getAllList();
  },
  beforeDestroy() {
    // this.$store.commit("app/setDataTypeTabsId", 2);
  },
  methods: {
    // 接口
    // 查询所有图册类型
    // async tAtlasTypeInfoFindAll() {
    //   let data = await this.$api.tAtlasTypeInfoFindAll();
    //   console.log(data);
    // },
    // 获取目标树未被单击下的数组
    // getAllList() {
    //   this.$api.tAtlasTypeInfoFindAll().then((res) => {
    //     // console.log(111, res);
    //     let arr = [];
    //     for (let i = 0; i < res.length; i++) {
    //       arr.push(res[i].id);
    //     }
    //     this.$api.getCurrentPhotoAlbum(arr).then((res) => {
    //       this.allList = res.slice(0, 9);
    //       this.allListTotal = res;
    //       this.arrList = res.slice(0, 9);
    //       this.listTotal = res;
    //     });
    //   });
    // },
    // 获取目标树下的数组
    async getCurrentPhotoAlbum(ids, name, pageNum) {
      let data = await this.$api.getCurrentPhotoAlbum({
        dataType: 1,
        ids: ids ? ids : this.pictureTreeChecked,
        name: name ? name : this.keyWords,
        pageSize: this.pageSize,
        pageNum: pageNum ? pageNum : this.current,
      });
      this.newList = data.list;
      this.total = data.total;
      // // console.log(222, data);
      // this.listTotal = data;
      // this.arrList = data.slice(0, 9);
      // // console.log(data[0].createDate.slice(0, 6));

      // 重新计算currentPage
      let totalPage = Math.ceil(this.total / this.pageSize);
      if (this.current > totalPage) {
        this.current = totalPage;
        this.getCurrentPhotoAlbum();
      }
      // 解决currentPage 不动态绑定的问题
      this.paginationKey = Math.random();
    },
    handError(){
      this.loading.close();
    }
    ,
    // 移除上传错误的文件
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList.pop(file);
    },

    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    // 查询
    search() {
      this.getCurrentPhotoAlbum(null, null, 1);
    },
    // 清空信息
    infoClean() {
      this.keyWords = "";
      this.getCurrentPhotoAlbum();
    },

    // 上传成功后加载组件隐藏
    handleSuccess(data, file, fileList) {
      this.loading.close();
      if (data.indexOf('500') != -1) {
        this.$message({
          type: 'error',
          message: data.split(',')[1],
          showClose: true
        })
        this.handleRemove(file)
        return;
      }
      this.fileList = fileList.slice(-1);
      console.log(this.fileList);
      this.fileList[0].url = require("@/assets/common/filepdf.jpg");
      // this.videoOptions.video.url = this.videoOptions.video.url + data;
      // const player = this.$refs.player.dp;
      // let url = `${window.VUE_APP_BASE_URL}/getVideo?videoPath=${data}`;
      // console.log(456, this.$refs.player.dp, url);
      // player.switchVideo({
      //   url: url,
      // });
    },
    // 上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    beforeUpload(file) {
      const sizeLimit = file.size / 1024 / 1024 / 1024 < 1; //这里做文件大小限制 1GB!
      if (!sizeLimit) {
        this.$message({
          message: "上传文件大小不能超过 1GB!",
          type: "warning",
          showClose: true
        });
        return false;
      }
      let reg =
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "word" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "wps" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "doc" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "docx" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "ppt" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "pptx" ||
        file.name
          .split(".")
          .pop()
          .toLowerCase() === "pdf";
      if (!reg) {
        this.$message({
          type: 'error',
          message: '上传图册只能是word格式、ppt格式、pdf格式！',
          showClose: true
        })
        return false;
      }

      this.loading = this.$loading({
        lock: true,
        text: "努力上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      console.log(file);

      return true;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.getCurrentPhotoAlbum();
      /* this.newList = this.list.slice((this.current - 1) * 9, this.current * 9);
      this.allList = this.list.slice((this.current - 1) * 9, this.current * 9);
      this.arrList = this.list.slice((this.current - 1) * 9, this.current * 9); */
    },
    // 编辑
    editPic(item) {
      /* if (this.pictureTreeChecked.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择图册类型!",
          showClose: true
        });
      } else {
      console.log(item); */
      this.editDialogVisible = true;
      this.title = "编辑";
      this.formLabelAlign.name = item.atlasName;
      this.formLabelAlign.memo = item.memo;
      this.formLabelAlign.id = item.id;
      this.fileList = [{ name: "", url: "", response: "" }];
      this.fileList[0].name = item.fileUrl.split("/").pop(0);
      this.fileList[0].response = item.fileUrl;
      this.fileList[0].url = require("@/assets/common/filepdf.jpg");
      // }
    },
    showSubmitLoading(){
       this.submitLoading = this.$loading({
          lock: true,
          text: "正在提交...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
    },
    // 编辑的提交
    editSubmit() {
      console.log(this.formLabelAlign);
      this.$refs.ruleForm2.validate((valid)=>{
        if(valid){
            if(this.fileList[0]){
                this.showSubmitLoading();
                this.$api
                .updatePhotoAlbum({
                  atlasName: this.formLabelAlign.name,
                  memo: this.formLabelAlign.memo,
                  id: this.formLabelAlign.id,
                  fileUrl: this.fileList[0].response,
                })
                .then(() => {
                  this.editDialogVisible = false;
                  this.submitLoading.close();
                  this.submitLoading = null;
                  this.$message({
                    type: "success",
                    message: "修改成功!",
                    showClose: true
                  });
                  this.getCurrentPhotoAlbum();
                });
            }else{
              this.$message({
                type: "warning",
                message: "请上传文件!",
                showClose: true
              });
            }
        }else{
          this.$message({
            type: "warning",
            message: "请正确填写表单!",
            showClose: true
          });
          return false;
        }
      })
    },
    // 新增
    addPic() {
      if (this.pictureTreeChecked.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择图册类型!",
          showClose: true
        });
      } else {
        this.addDialogVisible = true;
        this.fileList = [];
        this.addLabelAlign.name = "";
        this.addLabelAlign.memo = "";
        console.log(this.pictureTreeChecked, this.addLabelAlign);
      }
    },
    // 新增模态框的确认
    addSubmit() {
      console.log(this.addLabelAlign);
      this.$refs.ruleForm1.validate((valid)=>{
        if(valid){
            if(this.fileList[0]){
              this.showSubmitLoading();
              this.$api
                .savePhotoAlbum({
                  atlasName: this.addLabelAlign.name,
                  memo: this.addLabelAlign.memo,
                  pid: this.pictureTreeChecked[0],
                  fileUrl: this.fileList[0].response,
                })
                .then(() => {
                  this.submitLoading.close();
                  this.submitLoading = false;
                  this.getCurrentPhotoAlbum().then(() => {
                    this.addDialogVisible = false;
                    this.$message({
                      type: "success",
                      message: "添加成功!",
                      showClose: true
                    });
                  });
                });
            }else{
              this.$message({
                type: "warning",
                message: "请上传文件!",
                showClose: true
              });
            }
        }else{
          this.$message({
            type: "warning",
            message: "请正确填写表单!",
            showClose: true
          });
          return false;
        }
      })
    },
    // 删除
    deleteInfo(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api
            .deletePhotoAlbume({
              id: id,
            })
            .then(() => {
              this.$message({
                type: "success",
                message: "删除成功!",
                showClose: true
              });
              this.getCurrentPhotoAlbum();
              if (this.pictureTreeChecked.length === 0) {
                this.$api.getCurrentPhotoAlbum();
              } else {
                this.$api.getCurrentPhotoAlbum();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
            showClose: true
          });
        });
    },
  },
  components: {
    synchronization,
  },
};
</script>

<style lang="scss" scoped>
.page {
  position: relative;
  width: 99%;
  min-height: calc(100vh - 1.16rem);
  overflow: auto;
  // margin-left: 2.86rem;
}
.manage {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 0.1rem;
  margin-bottom: 0.1rem;
  .btn {
    width: 1rem;
    // height: 0.4rem;
    margin-right: 0.2rem;
    font-size: 0.16rem;
    background: #1890ff;
    border-radius: 0.05rem;
    // line-height: 0.4rem;
    text-align: center;
    font-size: 0.14rem;
    font-family: Alibaba PuHuiTi;
    font-weight: 400;
    color: #ffffff;
    border: none;
    i {
      // margin-right: 0.08rem;
    }
  }
  .search {
    margin-right: 0.2rem;
    width: 4rem;
    // height: 0.42rem;
    background: #034576;
    // border: 0.01rem solid #313030;
    padding-left: 0.02rem;
    border-radius: 0.05rem;
    .icon-search {
      margin-left: 0.1rem;
      background-image: url(~@/assets/images/search@2x.png);
      width: 0.14rem;
      height: 0.15rem;
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
    }
    ::v-deep.el-input__inner {
      color: white;
      // width: 80%;
      background: #034576;
      border: none;
      font-size: 0.12rem;
    }
  }
}
.listAll {
  margin-bottom: 0.4rem;
}
.listTitle {
  display: flex;
  height: 0.54rem;
  line-height: 0.54rem;
  font-size: 0.16rem;
  background: #034576;
  font-family: Alibaba PuHuiTi;
  font-weight: 400;
  color: #cccccc;
  li {
    width: 1.4rem;
    text-align: center;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  li:nth-of-type(1) {
    width: 0.6rem;
    margin: 0 0.2rem 0 0.16rem;
  }
  li:nth-of-type(2) {
    width: 2.4rem;
  }
  li:nth-of-type(3) {
    width: 5rem;
    padding: 0 1rem;
    margin: 0 0.7rem 0 0.1rem;
  }
  li:nth-of-type(5) {
    margin: 0 0.4rem;
  }
  li:nth-of-type(6) {
    width: 3.2rem;
  }
}
.list {
  ul {
    height: 0.54rem;
    line-height: 0.54rem;
    display: flex;
    font-size: 0.14rem;
    font-family: Alibaba PuHuiTi;
    font-weight: 400;
    color: #ffffff;
    li {
      width: 1.4rem;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    li:nth-of-type(1) {
      width: 0.6rem;
      margin: 0 0.2rem 0 0.16rem;
    }
    li:nth-of-type(2) {
      width: 2.4rem;
    }
    li:nth-of-type(3) {
      width: 5rem;
      padding: 0 1rem;
      margin: 0 0.7rem 0 0.1rem;
    }
    li:nth-of-type(5) {
      margin: 0 0.4rem;
    }
    li:nth-of-type(6) {
      width: 3.2rem;
      display: flex;
      padding: 0 0.5rem;
      div {
        width: 1rem;
        height: 0.32rem;
        background: #1890ff;
        border-radius: 0.05rem;
        margin-left: 0.1rem;
        line-height: 0.32rem;
        margin-top: 0.2rem;
        img {
          width: 0.14rem;
          height: 0.14rem;
          margin-top: 9%;
          margin-right: 0.06rem;
        }
        span {
          font-size: 0.14rem;
          font-family: Alibaba PuHuiTi;
          font-weight: 400;
          color: #ffffff;
        }
      }
      div:nth-of-type(3) {
        background: #e64f4f;
      }
    }
  }
}
::v-deep .el-dialog {
  color: #ffffff;
  font-size: 0.16rem;
  width: 7.2rem;
  background: #474747;
  box-shadow: 0rem 0rem 0.38rem 0rem rgba(0, 0, 0, 0.45);
  border-radius: 0.05rem;
  .el-dialog__header {
    padding: 0.16rem;
    background: #143853;
  }
  .el-dialog__title {
    color: #ffffff;
  }
  .el-dialog__body {
    color: #ffffff;
    background: #0f2d43;
  }
  .el-textarea__inner {
    background: #144f87;
    border: none;
    color: #ffffff;
  }
  .el-input__count {
    background: #144f87;
    color: #ffffff;
  }
  .el-form-item__label {
    color: #ffffff;
  }
  .el-input__inner {
    background: #0355a4;
    border: none;
    font-size: 0.14rem;
  }
  .el-dialog__wrapper {
    z-index: 3000;
    display: block;
  }
  input {
    color: #ffffff;
  }
  input::-webkit-input-placeholder {
    color: #ffffff;
  }
  input::-moz-input-placeholder {
    color: #ffffff;
  }
  input::-ms-input-placeholder {
    color: #ffffff;
  }
  .el-select {
    color: #ffffff;
    width: 100%;
    background: #0355a4;
    .el-input__inner {
      background: #0355a4;
    }
  }
  .footer {
    margin-top: 0.3rem;
    color: #ffffff;
    margin-right: 0.3rem;
    justify-content: flex-end;
    .cancel {
      text-align: center;
      width: 1.2rem;
      height: 0.38rem;
      line-height: 0.38rem;
      background: #62656c;
      border-radius: 0.05rem;
    }
    .confirm {
      margin-left: 0.2rem;
      text-align: center;
      width: 1.2rem;
      height: 0.38rem;
      line-height: 0.38rem;
      background: #1890ff;
      border-radius: 0.05rem;
    }
  }
}
.upload {
  display: flex;
  ::v-deep.el-upload-list__item {
    width: 4rem;
  }
}
.image-pagination {
  position: absolute;
  bottom: 0;
  right: 0;
  margin-right: 2.87rem;
  .el-pagination.is-background .el-pager li:not(.disabled).active {
    background-color: #1890ff;
    color: #ffffff;
  }
  .el-pagination.is-background .btn-prev,
  .el-pagination.is-background .btn-next,
  .el-pagination.is-background .el-pager li {
    background-color: #034475;
  }
  .el-pagination--small .el-pagination__editor.el-input .el-input__inner {
    background: #034475;
    border: 0px;
  }
  .el-pagination--small span:not([class*="suffix"]),
  .el-pagination--small button {
    color: #034475;
    margin-left: 20px;
  }
  .el-pagination .btn-prev .el-icon,
  .el-pagination .btn-next .el-icon {
    color: #ccc;
  }
  .el-pagination.is-background .el-pagination__total,
  .el-pagination.is-background .el-pagination__jump {
    color: #1890ff;
    font-weight: 700;
  }
  .el-pagination.is-background .el-pagination__jump .el-input__inner {
    color: #fff;
  }

  .el-pagination.is-background .btn-prev:hover .el-icon,
  .el-pagination.is-background .btn-next:hover .el-icon {
    color: #fff;
  }
  .el-pagination.is-background .el-pager .number:hover,
  .el-pagination.is-background .btn-prev:hover,
  .el-pagination.is-background .btn-next:hover {
    background-color: #1890ff;
    color: #ffffff;
  }
}
</style>
